import { NextRequest, NextResponse } from 'next/server'
import { getUser } from '@/lib/authUtils'
import prisma from '@/lib/prisma'
import fs from 'fs/promises'
import path from 'path'

export async function POST(request: NextRequest) {
  try {
    const userId = await getUser(request)
    if (!userId) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 })
    }
    if (userId instanceof NextResponse) {
      return userId
    }

    // 获取uploads目录路径
    const uploadsDir = path.join(process.cwd(), 'public', 'uploads')
    const rootUploadsDir = path.join(process.cwd(), 'uploads')
    
    let totalSizeBytes = 0
    let fileCount = 0
    const processedFiles: string[] = []

    // 统计public/uploads目录
    try {
      const files = await fs.readdir(uploadsDir)
      for (const file of files) {
        const filePath = path.join(uploadsDir, file)
        const stats = await fs.stat(filePath)
        if (stats.isFile()) {
          totalSizeBytes += stats.size
          fileCount++
          processedFiles.push(`public/uploads/${file}`)
        }
      }
    } catch (error) {
      console.log('public/uploads目录不存在或无法访问')
    }

    // 统计根目录uploads
    try {
      const files = await fs.readdir(rootUploadsDir)
      for (const file of files) {
        const filePath = path.join(rootUploadsDir, file)
        const stats = await fs.stat(filePath)
        if (stats.isFile()) {
          totalSizeBytes += stats.size
          fileCount++
          processedFiles.push(`uploads/${file}`)
        }
      }
    } catch (error) {
      console.log('uploads目录不存在或无法访问')
    }

    const totalSizeMB = Math.ceil(totalSizeBytes / (1024 * 1024))

    // 更新用户的存储使用量
    await prisma.vms_user.update({
      where: { id: userId },
      data: {
        storage_used: totalSizeMB
      }
    })

    return NextResponse.json({
      success: true,
      message: '存储使用量统计完成',
      data: {
        totalFiles: fileCount,
        totalSizeBytes,
        totalSizeMB,
        processedFiles
      }
    })
  } catch (error) {
    console.error('统计存储使用量失败:', error)
    return NextResponse.json(
      { error: '统计失败', details: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    )
  }
}